package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.SkuhasStockVo;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
     private ProductFeignService productFeignService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderFeignService orderFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        Object skuId = params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id", skuId);
        }
        Object wareId = params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
           queryWrapper.eq("ware_id",wareId); 
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper

        );
        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断如果没有这个库存就是新增记录
        List<WareSkuEntity> entites = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entites==null||entites.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(0);
            //远程查询sku的名称
            //TODO 1. 如果远程查询失败,整个事务无需回滚,自己catch异常不向上抛出
            //TODO 2. 还可以用什么办法出现异常不会滚呢
            try {
                R info = productFeignService.info(skuId);
                if(info.getCode()==0){
                  Map<String,Object>  data = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.baseMapper.insert( wareSkuEntity);
        }else{
            this.baseMapper.addStock(skuId,wareId,skuNum);

        }
    }

    @Override
    public List<SkuhasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuhasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuhasStockVo vo = new SkuhasStockVo();
            //查询当前sku的总库存量
            Long count = this.baseMapper.getStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁定库存
     * @param vo
     * @return
     * 默认只要是运行是异常都会回滚
     * rollbackFor=NoStockException.class
     * 库存解锁
     * 1.下单成功,订单过期没有支付系统自动取消,被用户手动取消
     * 2.下订单成功,库存锁定也成功,接下来的业务调用失败,导致订单回滚
     * 之前锁定的库存就要自动解锁
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单,追溯
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);
        //按照下单收获地址,知道一个就近仓库,库存锁定
        //找到每个商品再哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            //查询这个商品在哪里有库存
            List<Long> wareIds = this.baseMapper.listWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            stock.setSkuId(skuId);
            return stock;
        }).collect(Collectors.toList());
        //锁定库存
        Boolean allLock = true;
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds= hasStock.getWareId();
            if(CollectionUtils.isEmpty(wareIds)){
                throw new NoStockException(skuId);
            }
            //1.如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发送给MQ
            //2.如果锁定失败,前面保存的工作单信息就回滚了 ,发送出去的消息即使要解锁记录,由于去数据库查不到id,所以就不用解锁
            for (Long wareId : wareIds) {
                //成功就返回1否则返回0
                Long count = this.baseMapper.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count == 1) {
                    skuStocked = true;
                    //锁成功不要找其他仓库
                    //TODO 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(entity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    //只发id不行
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity, stockDetailTo);
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    break;
                }else{
                    //当前仓库重试下一个仓库

                }
            }
            if(skuStocked==false){
                //当前商品所有仓库都没有锁住
                throw  new NoStockException(skuId);
            }
        }
        //肯定全局锁定成功

        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        /**
         *  下单成功库存锁定成功,接下来的业务调用失败,导致订单回滚,之前的库存就要自动解锁
         *         2.订单失败
         *         查询数据库关于这个订单的锁定库存信息
         *         有: 证明库存锁定成功
         *         解锁情况:1. 没有这个订单,这个情况解锁
         *                 2.有这个订单.看订单状态,已取消:解锁库存 没取消:不能解锁
         *         没有:库存锁定失败了,库存回滚了,这种情况无需解锁
         */
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if(byId!=null){
            //解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();//根据订单号查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode()==0){
                OrderVo data = r.getData("data",new TypeReference<OrderVo>() {});
                //data==null不存在订单 status=4被取消
                if(data==null || data.getStatus()==4){
                    //订单已经被取消了,才能解锁库存
                    //当前库存工作单是已锁定但为解锁
                    if(byId.getLockStatus()==1){
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);

                    }
                }
            }else{
                throw new RuntimeException("调用远程服务失败");
            }
        }else{
            //无需解锁
        }
    }
    //防止订单服务卡顿,导致订单状态改不了,库存消息优先到期,查订单状态是新建状态
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查询下最新的库存解锁状态,防止重复解锁库存
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        //按照库存工作单找打所有没有解锁的库存,进行解锁
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", task.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());

        }

    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }
    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        //库存解锁
        this.baseMapper.unLockStock(skuId,wareId,num);
        //更新库存状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2); //变为已解锁
        wareOrderTaskDetailService.updateById(entity);
    }

}